﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Raven.Client;
using Genrsis.WorkitemTracking.Domain;

namespace Genrsis.WorkitemTracking.Web.Controllers
{
    public class ControllerBase : Controller
    {
        protected IDocumentStore DocumentStore { get; private set; }

        protected ControllerBase(IDocumentStore documentStore)
        {
            DocumentStore = documentStore;
        }

        protected User GetCurrentUser()
        {
            var membershipUser = Membership.GetUser(true);
            var membershipUserId = (int)membershipUser.ProviderUserKey;

            using (var session = DocumentStore.OpenSession())
            {
                var user = session.Query<User>()
                    .Where(u => u.MembershipUserId == membershipUserId)
                    .SingleOrDefault();

                // If no user was found, create one ready for next time...
                if (user == null)
                {
                    user = new User { MembershipUserId = membershipUserId, Username = membershipUser.UserName };
                    session.Store(user);
                    session.SaveChanges();
                }

                return user;
            }
        }
    }
}